package com.jackeysun.common_kit

import android.content.Context
import android.content.Intent
import android.graphics.*
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import com.jackeysun.common.go
import com.jackeysun.common_kit.databinding.ActivityMainBinding
import com.jackeysun.log.ConsoleFloaty
import com.jackeysun.log.FloatingPermission
import com.jackeysun.log.LogActivity
import com.jackeysun.log.LogFileActivity
import com.jackeysun.util.Application.mApplication
import com.jackeysun.util.SpExt.Storage
import com.jackeysun.util.getString
import com.jackeysun.util.put
import com.jackeysun.util.toast
import com.stardust.enhancedfloaty.FloatyService
import com.stardust.enhancedfloaty.ResizableExpandableFloatyWindow
import java.lang.RuntimeException


class MainActivity : AppCompatActivity() {

    private val TAG = "MainActivity"
    private lateinit var mBinding: ActivityMainBinding
    private lateinit var mFloatyWindow: ResizableExpandableFloatyWindow
    private val WINDOW_SHOW_LOCK = Any()
    private val mX = 0
    private  var mY:Int = 0

    @Volatile
    private var mShown = false
    private val handler = Handler(Looper.getMainLooper())
    private val runnable: Runnable by lazy {
        object : Runnable {
            override fun run() {
                Log.d(TAG, "onCreate: handler runnable")
                handler.postDelayed(this, 3000)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        mBinding.remove.setOnClickListener {
            Log.d(TAG, "onCreate: remove click")
            handler.removeCallbacks(runnable)
        }
        mBinding.post.setOnClickListener {
            Log.d(TAG, "onCreate: post click")
            handler.postDelayed(runnable, 3000)
        }

        mBinding.viewpager2.setOnClickListener {
            go(MainActivity4())
        }

        Storage.put("key", "b")
        val value = Storage.getString("key")
        value.toast()

        mBinding.log.setOnClickListener { go(LogFileActivity()) }

        val mConsoleFloaty = ConsoleFloaty()
        mFloatyWindow = object : ResizableExpandableFloatyWindow(mConsoleFloaty) {
            override fun onCreate(service: FloatyService?, manager: WindowManager?) {
                super.onCreate(service, manager)
                expand()
                mFloatyWindow.windowBridge.updatePosition(mX, mY)
//                synchronized(WINDOW_SHOW_LOCK) {
//                    mShown = true
//                    WINDOW_SHOW_LOCK.notifyAll()
//                }
            }
        }
        show()

        val viewWidth: Int = windowManager.defaultDisplay.width - dp2px(this, 20f)
        mBinding.tv.initWidth(viewWidth)
        mBinding.tv.setHasAnimation(true)
//        mBinding.tv.setCloseInNewLine(true)
        mBinding.tv.setOpenSuffixColor(Color.RED)
        mBinding.tv.setCloseSuffixColor(Color.RED)
        mBinding.tv.setOriginalText(
            """
                在全球，随着Flutter被越来越多的知名公司应用在自己的商业APP中，Flutter这门新技术也逐渐进入了移动开发者的视野，尤其是当Google在2018年IO大会上发布了第一个Preview版本后，国内刮起来一股学习Flutter的热潮。
                为了更好的方便帮助中国开发者了解这门新技术，我们，Flutter中文网，前后发起了Flutter翻译计划、Flutter开源计划，前者主要的任务是翻译Flutter官方文档，后者则主要是开发一些常用的包来丰富Flutter生态，帮助开发者提高开发效率。而时至今日，这两件事取得的效果还都不错！
                """.trimIndent()
        )
//        Toast("gg")
//        this Toast "gg"
//
//        ToastMiddle("gg")
//
//        ToastSingle("gg")

        mBinding.main1.setOnClickListener {
            "gg".toast()
            startActivity(
                Intent(this@MainActivity, MainActivity2::class.java)
            )
        }
        mBinding.main2.setOnClickListener {
            "gg".toast()
            startActivity(
                Intent(this@MainActivity, MainActivity3::class.java)
            )
        }

        mBinding.btn.setProgress(progress = 30)
    }

    private fun scaleBitmap(origin: Bitmap?, ratio: Float): Bitmap? {
        if (origin == null) {
            return null
        }
        val width = origin.width
        val height = origin.height
        val matrix = Matrix()
        matrix.preScale(ratio, ratio)
        val newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false)
        if (newBM == origin) {
            return newBM
        }
        origin.recycle()
        return newBM
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    fun dp2px(context: Context, dpValue: Float): Int {
        var res = 0
        val scale: Float = context.getResources().getDisplayMetrics().density
        res =
            if (dpValue < 0) (-(-dpValue * scale + 0.5f)).toInt() else (dpValue * scale + 0.5f).toInt()
        return res
    }

    private fun startFloatyService() {
        startService(Intent(this, FloatyService::class.java))
    }

    private fun show() {
        if (mShown) {
            return
        }
        if (!FloatingPermission.canDrawOverlays(this)) {
            FloatingPermission.manageDrawOverlays(this)
            this.toast(R.string.text_no_floating_window_permission)
            return
        }
        startFloatyService()
        FloatyService.addWindow(mFloatyWindow)
    }
}